package com.campus.backend.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.campus.backend.service.SessionService;
import com.campus.backend.vo.oss.OssStsVo;
import com.campus.common.bean.common.Resp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * OSS对象存储 前端控制器
 * </p>
 *
 * @author ZhaoYuJie
 * @since 2025-04-24
 */
@RestController
@RequestMapping("/oss")
public class OssController {

    private static final Logger log = LoggerFactory.getLogger(OssController.class);
    @Value("${oss.sts.endpoint}")
    private String endpoint;
    @Value("${oss.endpoint}")
    private String ossEndpoint;
    @Value("${oss.sts.access-key-id}")
    private String accessKeyId;
    @Value("${oss.sts.access-key-secret}")
    private String accessKeySecret;
    @Value("${oss.sts.role-arn}")
    private String roleArn;
    @Value("${oss.sts.duration-seconds}")
    private Long durationSeconds;
    @Value("${oss.bucket}")
    private String bucket;
    @Value("${oss.region}")
    private String region;

    @Autowired
    private SessionService sessionService;

    @GetMapping("/sts-token")
    public Resp<OssStsVo> getStsToken() {
        OssStsVo vo = new OssStsVo();
        Integer userId = sessionService.getUserInfo().getId();
        String roleSessionName = "Merchant_Upload_" + userId + "_" + System.currentTimeMillis();
        try {
            String regionId = "";
            DefaultProfile.addEndpoint(regionId, "Sts", endpoint);
            IClientProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
            DefaultAcsClient client = new DefaultAcsClient(profile);
            final AssumeRoleRequest request = new AssumeRoleRequest();
            request.setSysMethod(MethodType.POST);
            request.setRoleArn(roleArn);
            request.setRoleSessionName(roleSessionName);
            request.setPolicy(null);
            request.setDurationSeconds(durationSeconds);
            final AssumeRoleResponse response = client.getAcsResponse(request);
            vo.setAccessKeyId(response.getCredentials().getAccessKeyId());
            vo.setAccessKeySecret(response.getCredentials().getAccessKeySecret());
            vo.setSecurityToken(response.getCredentials().getSecurityToken());
            vo.setExpiration(response.getCredentials().getExpiration());
            vo.setRequestId(response.getRequestId());
            vo.setSuccess(true);
            vo.setBucket(bucket);
            vo.setRegion(region);
            vo.setEndpoint(ossEndpoint);
        } catch (ClientException e) {
            vo.setSuccess(false);
            vo.setErrorCode(e.getErrCode());
            vo.setErrorMessage(e.getErrMsg());
            vo.setRequestId(e.getRequestId());
            log.error("获取STS Token失败", e);
        }
        return Resp.success(vo);
    }

}
